package org.itboys.core.service.mysql.front;

import org.itboys.commons.ErrorException;
import org.itboys.commons.utils.time.TimeUtils;
import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.commons.utils.tools.LongUtil;
import org.itboys.core.common.ExceptionEnum;
import org.itboys.core.common.SundayCommonConstants;
import org.itboys.core.common.UserTypeEnum;
import org.itboys.core.common.WalletRecordEnum;
import org.itboys.core.dao.order.SundayRecycleOrderModelMapper;
import org.itboys.core.dao.order.SundayRecycleOrderTrayMapper;
import org.itboys.core.dao.order.SundaySendOrderModelMapper;
import org.itboys.core.dao.order.SundaySendOrderTrayMapper;
import org.itboys.core.dao.tray.SundayTrayMapper;
import org.itboys.core.dro.order.SundayRecycleOrderDro;
import org.itboys.core.dro.order.SundayRecycleOrderHarmRecordDro;
import org.itboys.core.dro.order.SundayRecycleOrderModelDro;
import org.itboys.core.dro.order.SundayRecycleOrderTrayDro;
import org.itboys.core.dto.order.SundayRecycleOrderDto;
import org.itboys.core.entity.mongo.SundayHarmRecord;
import org.itboys.core.entity.mongo.SundayMember;
import org.itboys.core.entity.mongo.SundayStore;
import org.itboys.core.entity.mysql.order.*;
import org.itboys.core.entity.mysql.tray.SundayTray;
import org.itboys.core.entity.mysql.tray.SundayTrayModel;
import org.itboys.core.service.mongo.front.SundayFrontHarmRecordService;
import org.itboys.core.service.mongo.web.SundayMemberService;
import org.itboys.core.service.mongo.web.SundayStoreService;
import org.itboys.core.service.mysql.web.SundayTrayModelService;
import org.itboys.core.service.mysql.web.SundayTrayService;
import org.itboys.core.util.DistanceUtils;
import org.itboys.core.util.NumberUtil;
import org.itboys.core.util.jxUtil.MapUtil;
import org.itboys.mysql.service.BaseMySqlService;
import org.itboys.param.ParamUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 作者：zzq
 * 时间：2018/12/11
 * 描述：回收订单
 */
@Service
public class SundayFrontRecycleOrderService extends BaseMySqlService<SundayRecycleOrder> {
    @Autowired
    private SundayFrontSendOrderService sendOrderService;
    @Autowired
    private SundaySendOrderModelMapper sendOrderModelMapper;
    @Autowired
    private SundayMemberService memberService;
    @Autowired
    private SundayTrayModelService modelService;
    @Autowired
    private SundayFrontRecycleOrderModelService orderModelService;
    @Autowired
    private SundayRecycleOrderModelMapper orderModelMapper;
    @Autowired
    private SundayRecycleOrderTrayMapper orderTrayMapper;
    @Autowired
    private SundayTrayService trayService;
    @Autowired
    private SundayFrontHarmRecordService harmRecordService;
    @Autowired
    private SundayStoreService storeService;
    @Autowired
    private SundaySendOrderTrayMapper sendOrderTrayMapper;
    @Autowired
    private SundayTrayMapper trayMapper;
    @Autowired
    private SundayFrontWalletRecordService walletRecordService;

    /**
     * 创建订单
     *
     * @param orderDro
     * @return
     */
    @Transactional
    public SundayRecycleOrderDto createOrder(SundayRecycleOrderDro orderDro) {
        logger.info(orderDro.toString());
        //匹配回收仓库   供应商
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("isDeleted", SundayCommonConstants.NO);
        param.put("cityId", orderDro.getRecycleCityId());
        List<SundayStore> stores = storeService.list(param);
        if (ListUtil.isNull(stores)) {
            throw new ErrorException(ExceptionEnum.RECYCLE_ORDER_STORE_EXCEPTION.getValue());
        }
        if (ListUtil.isNull(orderDro.getModels())) {
            throw new ErrorException(ExceptionEnum.PARAM_NOT_ENOUGH_EXCEPTION.getValue());
        }
        //选择最近的仓库
        SundayStore recycleStore = new SundayStore();
        if (stores.size() == 1) {
            recycleStore = stores.get(0);
        } else {
            Double distence = 100000000.0;
            Map<String, Double> sendMap = MapUtil.getLngAndLat(orderDro.getRecycleProvince() + orderDro.getRecycleCity() + orderDro.getRecycleDistrict() + orderDro.getRecycleAddress());
            Double longitude = sendMap.get("lng");
            Double latitude = sendMap.get("lat");
            for (SundayStore store : stores) {
                Double storeDistence = DistanceUtils.GetDistance(longitude, latitude, store.getLongitude(), store.getLatitude());
                if (distence > storeDistence) {
                    recycleStore = store;
                    distence = storeDistence;
                }
            }
        }

        //生成订单
        SundayRecycleOrder order = new SundayRecycleOrder();
        SundaySendOrder sendOrder = sendOrderService.find(orderDro.getSendOrderId());
        param.clear();
        param.put("isDeleted", SundayCommonConstants.NO);
        param.put("orderId", sendOrder.getId());
        List<SundaySendOrderModel> sendOrderModels = sendOrderModelMapper.select(param);
        SundayMember member = memberService.getById(sendOrder.getMemberId());
        order.setOrderNo(NumberUtil.generateNumber("RECYCLE"));
        order.setStatus(SundayCommonConstants.recycle_order_status_dqr);
        order.setSendOrderId(sendOrder.getId());
        order.setSendOderNo(sendOrder.getOrderNo());
        order.setServiceId(recycleStore.getMemberId());
        order.setServiceName(recycleStore.getMemberName());
        order.setStoreId(recycleStore.getId());
        order.setStoreName(recycleStore.getName());
        order.setStoreAddress(recycleStore.getProvinceName()+recycleStore.getCityName()+recycleStore.getDistrictName()+recycleStore.getAddress());
        order.setType(sendOrder.getType());
        order.setMemberId(member.getId());
        order.setMemberName(member.getNickName());
        order.setMobile(member.getMobile());
        order.setRecycleDate(orderDro.getRecycleDate());
        order.setRecycleProvinceId(orderDro.getRecycleProvinceId());
        order.setRecycleProvince(orderDro.getRecycleProvince());
        order.setRecycleCityId(orderDro.getRecycleCityId());
        order.setRecycleCity(orderDro.getRecycleCity());
        order.setRecycleDistrictId(orderDro.getRecycleDistrictId());
        order.setRecycleDistrict(orderDro.getRecycleDistrict());
        order.setRecycleAddress(orderDro.getRecycleAddress());
        //统计时间  天数
        Date receiveDate = sendOrder.getReceiveTime();
        Date now = new Date();
        long diff = now.getTime() - receiveDate.getTime();
        long days = diff / (1000 * 60 * 60 * 24);
        days = days <= 0 ? 1 : days;
        BigDecimal totalAmount = new BigDecimal("0");
        // 统计收入
        for (SundayRecycleOrderModelDro modelDro : orderDro.getModels()) {
            //是否为订单模板的一种
            Integer isPartOrder = 0;
            for (SundaySendOrderModel sendOrderModel : sendOrderModels) {
                if (modelDro.getModelId().longValue() == sendOrderModel.getModelId().longValue()) {
                    totalAmount = totalAmount.add(sendOrderModel.getRentPrice().multiply(new BigDecimal(days)).multiply(new BigDecimal(modelDro.getNum())));
                    isPartOrder = 1;
                    break;
                }
            }
            if (isPartOrder == 0) {
                throw new ErrorException(ExceptionEnum.RECYCLE_ORDER_MODEL_EXCEPTION.getValue());
            }
        }
        order.setTotalAmount(totalAmount);
        order.setStartTime(TimeUtils.formatToTime(receiveDate));
        order.setEndTime(TimeUtils.formatToTime(now));
        order.setTime(days);
        //保存订单
        super.insert(order);
        //Integer isFull = 0;

        //保存订单托盘模板    更新配送模板数量   判断是否全部回收
        List<SundayRecycleOrderModel> orderModels = new ArrayList<>();
        //扣除的押金
        BigDecimal depositAmount=BigDecimal.ZERO;
        for (SundayRecycleOrderModelDro modelDro : orderDro.getModels()) {
            String modelName="";
            BigDecimal rentPrice=BigDecimal.ZERO;
            //修改配送订单模板数量
            for (SundaySendOrderModel sendOrderModel : sendOrderModels) {
                if (modelDro.getModelId().longValue() == sendOrderModel.getModelId().longValue()) {
                    if (modelDro.getNum() > sendOrderModel.getNum()) {
                        throw new ErrorException(ExceptionEnum.RECYCLE_ORDER_MODEL_NUM_EXCEPTION.getValue());
                    }
                    modelName=sendOrderModel.getName();
                    rentPrice=sendOrderModel.getRentPrice();
                    sendOrderModel.setNum(sendOrderModel.getNum() - modelDro.getNum());
                  /*  if (sendOrderModel.getNum() == 0) {
                        isFull = 1;
                    } else {
                        isFull = 0;
                    }*/
                    depositAmount = depositAmount.add(sendOrderModel.getDepositPrice().multiply(new BigDecimal(modelDro.getNum())));
                    sendOrderModelMapper.update(sendOrderModel);
                    break;
                }
            }
            SundayRecycleOrderModel orderModel = new SundayRecycleOrderModel(order.getId(), modelDro.getModelId(), modelName, modelDro.getNum(),modelDro.getNum(),rentPrice);
            orderModels.add(orderModel);

        }
        //批量新增订单模板
        orderModelMapper.batchInsert(orderModels);
        //配送订单全部回收了
       /* if (orderDro.getModels().size() == sendOrderModels.size() && isFull == 1) {
            sendOrder.setStatus(SundayCommonConstants.send_order_status_yhs);
        }*/
        //扣减配送订单租赁费
        sendOrder.setRentAmount(sendOrder.getRentAmount().subtract(totalAmount));
        //扣除押金
       /* if(sendOrder.getDepositAmount()!=null&&sendOrder.getDepositAmount().compareTo(BigDecimal.ZERO)==1){
            sendOrder.setDepositAmount(sendOrder.getDepositAmount().subtract(depositAmount));
        }*/
        sendOrderService.update(sendOrder);

        return packageSingleDto(order, null);

    }

    /**
     * 确认订单
     *
     * @param orderId
     * @param serviceId
     */
    public SundayRecycleOrderDto confirmOrder(Long orderId, Long serviceId) {
        SundayRecycleOrder order = super.find(orderId);
        checkOrderStatus(order, SundayCommonConstants.recycle_order_status_dqr);
        checkOrderService(order, serviceId);
        order.setStatus(SundayCommonConstants.recycle_order_status_yqr);
        order.setConfirmTime(new Date());
        super.update(order);
        return packageSingleDto(order, null);
    }

    /**
     * 回收订单  扫码
     *
     * @param trayDro
     * @return
     */
    @Transactional
    public SundayRecycleOrderDto recycleOrder(SundayRecycleOrderTrayDro trayDro) {
        System.out.println(trayDro.toString());
        SundayRecycleOrder order = super.find(trayDro.getOrderId());
        checkOrderStatus(order, SundayCommonConstants.recycle_order_status_yqr);
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("isDeleted", SundayCommonConstants.NO);
        param.put("orderId", trayDro.getOrderId());
        List<SundayRecycleOrderModel> orderModels = orderModelService.select(param);
        param.clear();
        param.put("orderId", order.getSendOrderId());
        List<SundaySendOrderModel> sendOrderModels = sendOrderModelMapper.select(param);
        List<Long> trayIds = trayDro.getTrayIds();
        param.clear();
        param.put("ids", trayIds);
        List<SundayTray> trays = trayService.select(param);
        List<SundayRecycleOrderHarmRecordDro> records = trayDro.getHarmRecords();
        List<Long> harmTrayIds = new ArrayList<>();
        List<SundayTray> harmTrays = new ArrayList<>();
        if (ListUtil.isNotNull(records)) {
            harmTrayIds = records.stream().map(e -> e.getTrayId()).collect(Collectors.toList());
            param.clear();
            param.put("ids", harmTrayIds);
            harmTrays = trayService.select(param);
        }
        BigDecimal totalAmount=BigDecimal.ZERO;
        //判断数量
        for (SundayRecycleOrderModel orderModel : orderModels) {
            Integer modelNum = 0;
            for (SundayTray tray : trays) {
                //判断托盘状态
                if (tray.getStatus() != SundayCommonConstants.tray_status_zlz) {
                    throw new ErrorException(ExceptionEnum.TRAY_STATUS_EXCEPTION.getValue());
                }
                if (tray.getModelId().longValue() == orderModel.getModelId().longValue()) {
                    modelNum++;
                }
            }
            if (ListUtil.isNotNull(harmTrays)) {
                for (SundayTray tray : harmTrays) {
                    //判断托盘状态
                    if (tray.getStatus() != SundayCommonConstants.tray_status_zlz) {
                        throw new ErrorException(ExceptionEnum.TRAY_STATUS_EXCEPTION.getValue());
                    }
                    if (tray.getModelId().longValue() == orderModel.getModelId().longValue()) {
                        modelNum++;
                    }
                }
            }
            //如果实际回收数量不足   则返回配送模板的数量
            if (modelNum < orderModel.getNum()) {
                Integer addNum=orderModel.getNum()-modelNum;
                for (SundaySendOrderModel sendOrderModel :sendOrderModels) {
                    if(sendOrderModel.getModelId().longValue()==orderModel.getModelId().longValue()){
                        sendOrderModel.setNum(sendOrderModel.getNum()+addNum);
                        sendOrderModelMapper.update(sendOrderModel);
                        break;
                    }
                }
                //throw new ErrorException(ExceptionEnum.RECYCLE_ORDER_MODEL_NUM_EXCEPTION.getValue());
            }
            //更新回收模板真实数量
            orderModel.setNum(modelNum);
            orderModelMapper.update(orderModel);
            //计算真实收益
            totalAmount = totalAmount.add(orderModel.getRentPrice().multiply(new BigDecimal(order.getTime())).multiply(new BigDecimal(modelNum)));
        }

        //增加订单托盘
        List<SundayRecycleOrderTray> orderTrays = new ArrayList<>();
        for (SundayTray tray : trays) {
            orderTrays.add(new SundayRecycleOrderTray(trayDro.getOrderId(), tray.getId(), SundayCommonConstants.recycle_order_tray_status_hsz));
        }
        //报废托盘   批量更新托盘状态
        if (ListUtil.isNotNull(harmTrays)) {
            param.clear();
            param.put("status", SundayCommonConstants.tray_status_ysh);
            trayMapper.batchUpdateFields(param, harmTrayIds);
        }
        //增加报废记录
        List<SundayHarmRecord> harmRecords = new ArrayList<>();
        if (ListUtil.isNotNull(records)) {
            for (SundayRecycleOrderHarmRecordDro dro : records) {
                trayIds.add(dro.getTrayId());
                harmRecords.add(new SundayHarmRecord(dro.getTrayId(), dro.getImage()));
                orderTrays.add(new SundayRecycleOrderTray(trayDro.getOrderId(), dro.getTrayId(), SundayCommonConstants.recycle_order_tray_status_ysh));
            }
        }
        //更新配送订单托盘状态
        param.clear();
        param.put("trayIds", trayIds);
        param.put("orderId", order.getSendOrderId());
        List<SundaySendOrderTray> sendOrderTrays = sendOrderTrayMapper.select(param);
        List<Long> orderTrayIds = new ArrayList<>();

        if (ListUtil.isNull(sendOrderTrays)) {
            throw new ErrorException(ExceptionEnum.RECYCLE_ORDER_TRAY_EXCEPTION.getValue());
        }
        for (Long trayId : trayIds) {
            //判断回收订单托盘是否在配送订单托盘内
            Integer isPartOrder = 0;
            for (SundaySendOrderTray orderTray : sendOrderTrays) {
                if (trayId.longValue() == orderTray.getTrayId().longValue()) {
                    isPartOrder = 1;
                    orderTrayIds.add(orderTray.getId());
                    break;
                }
            }
            if (isPartOrder == 0) {
                throw new ErrorException(ExceptionEnum.RECYCLE_ORDER_TRAY_EXCEPTION.getValue());
            }
        }
        param.clear();
        param.put("status", SundayCommonConstants.send_order_tray_status_yht);
        sendOrderTrayMapper.batchUpdateFields(param, orderTrayIds);

        orderTrayMapper.batchInsert(orderTrays);
        harmRecordService.batchSave(harmRecords);

        order.setTotalAmount(totalAmount);
        order.setStatus(SundayCommonConstants.recycle_order_status_yhs);
        order.setSendTime(new Date());
        super.update(order);
        return packageSingleDto(order, null);
    }

    /**
     * 扫码校检
     * @param orderId
     * @param modelId
     * @param trayId
     */
    public void scan(Long orderId,Long modelId,Long trayId){
        SundayTray tray = trayMapper.find(trayId);
        //判断托盘状态
        if (tray.getStatus() != SundayCommonConstants.tray_status_zlz) {
            throw new ErrorException(ExceptionEnum.TRAY_STATUS_EXCEPTION.getValue());
        }
        //判断托盘模板
        if(tray.getModelId().longValue()!=modelId.longValue()){
            throw new ErrorException(ExceptionEnum.TRAY_MODEL_EXCEPTION.getValue());
        }
        SundayRecycleOrder recycleOrder=super.find(orderId);
        SundaySendOrder sendOrder = sendOrderService.find(recycleOrder.getSendOrderId());
        Map<String,Object> param=new HashMap<String,Object>();
        param.put("isDeleted",SundayCommonConstants.NO);
        param.put("trayId",trayId);
        param.put("orderId", sendOrder.getId());

        Long num=Long.valueOf(sendOrderTrayMapper.count(param).toString());
        if(LongUtil.isZreo(num)){
            throw new ErrorException(ExceptionEnum.RECYCLE_ORDER_TRAY_EXCEPTION.getValue());
        }
    }

    /**
     * 订单收货
     *
     * @param orderId
     * @return
     */
    @Transactional
    public SundayRecycleOrderDto receiveOrder(Long orderId, Long serviceId) {
        SundayRecycleOrder order = super.find(orderId);
        checkOrderStatus(order, SundayCommonConstants.recycle_order_status_yhs);
        checkOrderService(order, serviceId);
        //返回库存   更新托盘状态
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("isDeleted", SundayCommonConstants.NO);
        param.put("orderId", orderId);
        List<SundayRecycleOrderTray> orderTrays = orderTrayMapper.select(param);
        List<Long> trayIds = orderTrays.stream().map(e -> e.getTrayId()).collect(Collectors.toList());
        List<Long> orderTrayIds = new ArrayList<>();
        //批量更新托盘状态
        param.clear();
        param.put("status", SundayCommonConstants.tray_status_dzl);
        param.put("storeId", order.getStoreId());
        param.put("serviceId", order.getServiceId());
        trayMapper.batchUpdateFields(param, trayIds);
        //批量更新回收订单托盘状态
        for (SundayRecycleOrderTray orderTray : orderTrays) {
            if (orderTray.getStatus() == SundayCommonConstants.recycle_order_tray_status_hsz) {
                orderTrayIds.add(orderTray.getId());
            }
        }
        param.clear();
        param.put("status", SundayCommonConstants.recycle_order_tray_status_yhs);
        orderTrayMapper.batchUpdateFields(param, orderTrayIds);

        //统计收益
        BigDecimal totalAmount = order.getTotalAmount();
        param.clear();
        param.put("orderId", orderId);
        List<SundayRecycleOrderModel> orderModels = orderModelMapper.select(param);
        List<Long> modelIds = orderModels.stream().map(e -> e.getModelId()).collect(Collectors.toList());
        param.clear();
        param.put("ids", modelIds);
        List<SundayTrayModel> models = modelService.select(param);
        SundaySendOrder sendOrder = sendOrderService.find(order.getSendOrderId());
        param.clear();
        param.put("ids", trayIds);
        List<SundayTray> trays = trayMapper.select(param);
        param.clear();
        List<Long> ownerIds=trays.stream().map(e -> e.getOwnerId()).collect(Collectors.toList());
        param.clear();
        param.put("id in", ownerIds);
        List<SundayMember> owners = memberService.list(param);
        //持有商的收益
        //根据每个托盘  产生10%的收益
        BigDecimal oneAmount = totalAmount.multiply(new BigDecimal("0.1")).divide(new BigDecimal(trays.size()));
        for (SundayMember member :owners) {
            BigDecimal incomeAmount=BigDecimal.ZERO;
            for (SundayTray tray :trays) {
                if(member.getId()==tray.getOwnerId().longValue()){
                    incomeAmount=incomeAmount.add(oneAmount);
                }
            }
            Long recordId=walletRecordService.createWalletRecord(member.getId(), incomeAmount.setScale(2,BigDecimal.ROUND_DOWN),
                    1, WalletRecordEnum.CHIYOUSHANG,order.getOrderNo());
            walletRecordService.executeWalletRecord(recordId);
        }
        //回收商的收益
        SundayMember recycleMember = memberService.getById(order.getServiceId());
        //产生totalAmount  20%的收益
        Long recycleRecordId=walletRecordService.createWalletRecord(recycleMember.getId(), totalAmount.multiply(new BigDecimal("0.2").setScale(2,BigDecimal.ROUND_DOWN)),
                1, WalletRecordEnum.HUISHOUSHANG,order.getOrderNo());
        walletRecordService.executeWalletRecord(recycleRecordId);
        //配送商的收益
        //产生totalAmount  50%的收益
        SundayMember sendMember = memberService.getById(sendOrder.getServiceId());
        Long sendRecordId=walletRecordService.createWalletRecord(sendMember.getId(), totalAmount.multiply(new BigDecimal("0.5").setScale(2,BigDecimal.ROUND_DOWN)),
                1 , WalletRecordEnum.PEISONGSHANG, sendOrder.getOrderNo());
        walletRecordService.executeWalletRecord(sendRecordId);
        //如果普通租客租赁    返回押金
        SundayMember member = memberService.getById(order.getMemberId());
        if(sendOrder.getDepositAmount()!=null&&sendOrder.getDepositAmount().compareTo(BigDecimal.ZERO)==1){
            BigDecimal returnAmount = BigDecimal.ZERO;
            for (SundayRecycleOrderModel orderModel : orderModels) {
                for (SundayTrayModel model : models) {
                    if (orderModel.getModelId().longValue() == model.getId().longValue()) {
                        returnAmount=returnAmount.add(model.getDepositPrice().multiply(new BigDecimal(orderModel.getNum())));
                        break;
                    }
                }
            }
            //返回押金
            walletRecordService.executeWalletRecord(walletRecordService.createWalletRecord(member.getId(), returnAmount.setScale(2,BigDecimal.ROUND_DOWN), 1
                    , WalletRecordEnum.YAJINTUIHUAN, sendOrder.getOrderNo()));
            sendOrder.setDepositAmount(sendOrder.getDepositAmount().subtract(returnAmount));
            sendOrderService.update(sendOrder);
        }
        param.clear();
        param.put("sendOrderId", sendOrder.getId());
        List<SundayRecycleOrder> orders = super.select(param);
        List<Long> orderIds=orders.stream().map(e->e.getId()).collect(Collectors.toList());
        Integer isReturn=1;
        //判断是否还存在待收盘的回收订单   如果有则暂不退租金
        for (SundayRecycleOrder recycleOrder :orders) {
            if(recycleOrder.getId().longValue()!=orderId.longValue()
                    &&recycleOrder.getStatus()!=SundayCommonConstants.recycle_order_status_ysp){
                isReturn=0;
                break;
            }
        }
        param.clear();
        param.put("isDeleted", SundayCommonConstants.NO);
        param.put("orderId", sendOrder.getId());
        Long sendOrderTrayNum = Long.valueOf(sendOrderTrayMapper.count(param).toString());
        param.clear();
        param.put("isDeleted", SundayCommonConstants.NO);
        param.put("orderIds", orderIds);
        Long recycleOrderTrayNum = Long.valueOf(orderTrayMapper.count(param).toString());
        //如果回收托盘数等于配送托盘数   并且不存在待收盘的回收订单订单   则配送订单已完成
        if(sendOrderTrayNum.longValue()==recycleOrderTrayNum&&isReturn==1){
            sendOrder.setStatus(SundayCommonConstants.send_order_status_ywc);
            BigDecimal totalOrderAmount=BigDecimal.ZERO;
            for (SundayRecycleOrder recycleOrder :orders) {
                totalOrderAmount = totalOrderAmount.add(recycleOrder.getTotalAmount());
            }
            //如果租金大于回收订单总收益 并且类型为日租   并且还有剩余租金   则退还剩余租金
            if(sendOrder.getTotalAmount().compareTo(totalOrderAmount)==1&&
                    sendOrder.getType()==SundayCommonConstants.rent_type_day){
                //返回租金
                walletRecordService.executeWalletRecord(walletRecordService.createWalletRecord(member.getId(), sendOrder.getTotalAmount().subtract(totalOrderAmount).setScale(2,BigDecimal.ROUND_DOWN), 1
                        , WalletRecordEnum.ZUJINTUHUAN, sendOrder.getOrderNo()));
                sendOrder.setRentAmount(totalOrderAmount);
            }
            sendOrderService.update(sendOrder);
        }

        order.setReceiveTime(new Date());
        order.setStatus(SundayCommonConstants.recycle_order_status_ysp);
        super.update(order);
        return packageSingleDto(order, null);
    }

    public SundayRecycleOrderDto findOne(Long orderId) {
        return packageSingleDto(super.find(orderId), null);
    }

    public List<SundayRecycleOrderDto> selectOrders(HttpServletRequest request, Long memberId, Integer status) {
        Map<String, Object> param = ParamUtil.packageMysqlPageParam(request, "orderNo");
        SundayMember member = memberService.getById(memberId);
        if(member.getUserType()==UserTypeEnum.SUPPLIER.getCode()){
            param.put("serviceId", memberId);
        }else {
            param.put("memberId", memberId);
        }
        if (status != 0) {
            param.put("status", status);
        }
        List<SundayRecycleOrder> orders = super.select(param);
        return packageMultiDto(orders);
    }

    public List<SundayRecycleOrderDto> packageMultiDto(List<SundayRecycleOrder> orders) {
        List<SundayRecycleOrderDto> dtos = new ArrayList<>();
        List<Long> orderIds = new ArrayList<>();
        for (SundayRecycleOrder order : orders) {
            orderIds.add(order.getId());
        }
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("orderIds", orderIds);
        List<SundayRecycleOrderModel> orderModels = orderModelService.select(param);
        for (SundayRecycleOrder order : orders) {
            List<SundayRecycleOrderModel> models = new ArrayList<SundayRecycleOrderModel>();
            for (SundayRecycleOrderModel orderModel : orderModels) {
                if (orderModel.getOrderId().longValue() == order.getId()) {
                    models.add(orderModel);
                }
            }
            dtos.add(packageSingleDto(order, models));
        }
        return dtos;
    }

    /**
     * 组装单个
     *
     * @param order
     * @return
     */
    private SundayRecycleOrderDto packageSingleDto(SundayRecycleOrder order, List<SundayRecycleOrderModel> models) {
        SundayRecycleOrderDto dto = new SundayRecycleOrderDto();
        if (ListUtil.isNull(models)) {
            Map<String, Object> param = new HashMap<String, Object>();
            param.put("orderId", order.getId());
            models = new ArrayList<SundayRecycleOrderModel>();
            for (SundayRecycleOrderModel orderModel : orderModelService.select(param)) {
                if (orderModel.getOrderId().longValue() == order.getId()) {
                    models.add(orderModel);
                }
            }
        }
        BeanUtils.copyProperties(order, dto);
        dto.setTotalAmount(order.getTotalAmount().setScale(2,BigDecimal.ROUND_DOWN ));
        dto.setModels(orderModelService.packageMultiDto(models));
        return dto;
    }


    /**
     * 核对订单状态
     *
     * @param order
     * @param orderStatus
     * @return
     */
    public SundayRecycleOrder checkOrderStatus(SundayRecycleOrder order, Integer orderStatus) {
        if (order.getStatus() != orderStatus) {
            throw new ErrorException(ExceptionEnum.RECYCLE_ORDER_STATUS_EXCEPTION.getValue());
        }
        return order;
    }


    /**
     * 核对供应商
     *
     * @param order
     * @param serviceId
     * @return
     */
    public SundayRecycleOrder checkOrderService(SundayRecycleOrder order, Long serviceId) {
        if (order.getServiceId().longValue() != serviceId.longValue()) {
            throw new ErrorException(ExceptionEnum.RECYCLE_ORDER_SERVICE_EXCEPTION.getValue());
        }
        return order;
    }


    /**
     * 核对用户
     *
     * @param order
     * @param memberId
     * @return
     */
    public SundayRecycleOrder checkOrderMember(SundayRecycleOrder order, Long memberId) {
        if (order.getMemberId().longValue() != memberId.longValue()) {
            throw new ErrorException(ExceptionEnum.RECYCLE_ORDER_MEMBER_EXCEPTION.getValue());
        }
        return order;
    }

}
